{% extends 'myadmin/base.html' %}
{% block main_body %}
<style>
    .form-card {
        background: #fff;
        border-radius: 6px;
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        padding: 20px;
    }
    .form-section {
        margin-bottom: 20px;
        padding-bottom: 15px;
        border-bottom: 1px solid #f1f1f1;
    }
    .form-row {
        display: flex;
        flex-wrap: wrap;
        margin: 0 -10px;
    }
    .form-col {
        flex: 1;
        min-width: 300px;
        padding: 0 10px;
        box-sizing: border-box;
    }
    .form-group {
        margin-bottom: 12px;
        width: 100%;
    }
    .form-group label {
        font-weight: 600;
        font-size: 13px;
        margin-bottom: 5px;
        display: block;
    }
    .form-control {
        width: 100%;
        padding: 6px 10px;
        font-size: 13px;
        height: 34px;
        box-sizing: border-box;
        border: 1px solid #ccc;
        border-radius: 4px;
    }
    textarea.form-control {
        height: auto;
        min-height: 80px;
        resize: vertical;
    }
    .required-mark {
        color: #dd4b39;
        margin-left: 3px;
    }
    .meal-card {
        border: 1px solid #f1f1f1;
        border-radius: 4px;
        padding: 15px;
        margin-bottom: 15px;
        position: relative;
    }
    .remove-meal {
        position: absolute;
        top: 5px;
        right: 10px;
        color: #dd4b39;
        background: none;
        border: none;
        cursor: pointer;
        font-size: 16px;
    }
    .add-meal-btn {
        margin-top: 10px;
        background-color: #00a65a;
        color: white;
        border: none;
        padding: 6px 12px;
        border-radius: 4px;
        cursor: pointer;
    }
    .add-meal-btn:hover {
        background-color: #008d4c;
    }
    .btn-group {
        margin-top: 15px;
        display: flex;
        gap: 10px;
        justify-content: flex-end;
    }
    .errorlist {
        color: #dd4b39;
        list-style: none;
        padding: 0;
        margin: 5px 0;
        font-size: 12px;
    }
    /* 食物选择下拉框核心样式 - 两条线组成的箭头 */
    .food-select-wrapper {
        position: relative;
    }
    .food-select-btn {
        width: 100%;
        padding: 6px 10px;
        padding-right: 25px; /* 为箭头留空间 */
        font-size: 13px;
        height: 34px;
        box-sizing: border-box;
        border: 1px solid #ccc;
        border-radius: 4px;
        background: white;
        text-align: left;
        cursor: pointer;
    }
    /* 关键：用两条线组成箭头，不是三角形 */
    .food-select-btn:after {
        content: "";
        position: absolute;
        right: 6px;
        top: 50%;
        width: 6px;
        height: 6px;
        border-right: 1.5px solid #666;
        border-bottom: 1.5px solid #666;
        transform: translateY(-70%) rotate(45deg); /* 旋转45度形成箭头 */
        pointer-events: none;
    }
    .food-dropdown {
        position: absolute;
        top: 100%;
        left: 0;
        right: 0;
        max-height: 250px;
        overflow-y: auto;
        border: 1px solid #ccc;
        border-top: none;
        border-radius: 0 0 4px 4px;
        background: white;
        z-index: 10;
        display: none;
    }
    .food-dropdown.active {
        display: block;
    }
    .food-item {
        padding: 8px 12px;
        cursor: pointer;
    }
    .food-item:hover {
        background-color: #f0f7ff;
    }
    .food-item.selected {
        background-color: #e1f0fa;
        font-weight: bold;
    }
</style>
<section class="content-header">
    <h1>饮食计划管理 <small>添加饮食计划</small></h1>
    <ol class="breadcrumb">
        <li><a href="#"><i class="fa fa-home"></i> 首页</a></li>
        <li><a href="#">饮食计划管理</a></li>
        <li class="active">添加饮食计划</li>
    </ol>
</section>
<section class="content">
    <div class="row">
        <div class="col-md-12">
            <div class="box box-primary">
                <div class="box-header with-border">
                    <h3 class="box-title">饮食计划信息录入</h3>
                </div>
                <form method="post" action="{% url 'myadmin_dietplan_insert' %}" class="form-card" id="dietPlanForm">
                    {% csrf_token %}
                    <!-- 表单集管理字段 -->
                    <input type="hidden" name="form-TOTAL_FORMS" value="1" id="id_form-TOTAL_FORMS">
                    <input type="hidden" name="form-INITIAL_FORMS" value="0" id="id_form-INITIAL_FORMS">
                    <input type="hidden" name="form-MIN_NUM_FORMS" value="0" id="id_form-MIN_NUM_FORMS">
                    <input type="hidden" name="form-MAX_NUM_FORMS" value="1000" id="id_form-MAX_NUM_FORMS">
                    <!-- 计划基本信息 -->
                    <div class="form-section">
                        <h4><i class="fa fa-calendar"></i> 计划基本信息</h4>
                        <div class="form-row">
                            <div class="form-col">
                                <div class="form-group">
                                    <label>所属用户 <span class="required-mark">*</span></label>
                                    <select name="user_id" class="form-control" required>
                                    {% for user in users %}
                                    <option value="{{ user.user_id }}">
                                        {{ user.username }} (ID: {{ user.user_id }})
                                    </option>
                                    {% endfor %}
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label>计划名称 <span class="required-mark">*</span></label>
                                    <input type="text" 
                                           name="plan_name" 
                                           class="form-control" 
                                           required>
                                </div>
                            </div>
                            <div class="form-col">
                                <div class="form-group">
                                    <label>计划备注</label>
                                    <textarea name="notes" class="form-control" rows="5"></textarea>
                                </div>
                                <!-- 营养目标设置 -->
                                <div class="form-row">
                                    <div class="form-col" style="flex: 0 0 50%;">
                                        <div class="form-group">
                                            <label>目标热量（大卡）</label>
                                            <input type="number" 
                                                   name="target_calories" 
                                                   class="form-control">
                                        </div>
                                    </div>
                                    <div class="form-col" style="flex: 0 0 50%;">
                                        <div class="form-group">
                                            <label>目标蛋白质（g）</label>
                                            <input type="number" 
                                                   name="protein_target" 
                                                   step="0.01" 
                                                   class="form-control">
                                        </div>
                                    </div>
                                </div>
                                <div class="form-row">
                                    <div class="form-col" style="flex: 0 0 50%;">
                                        <div class="form-group">
                                            <label>目标碳水（g）</label>
                                            <input type="number" 
                                                   name="carbs_target" 
                                                   step="0.01" 
                                                   class="form-control">
                                        </div>
                                    </div>
                                    <div class="form-col" style="flex: 0 0 50%;">
                                        <div class="form-group">
                                            <label>目标脂肪（g）</label>
                                            <input type="number" 
                                                   name="fat_target" 
                                                   step="0.01" 
                                                   class="form-control">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- 餐次详情 -->
                    <div class="form-section">
                        <h4><i class="fa fa-cutlery"></i> 餐次详情（每100克）</h4>
                        <div id="meal-container">
                            <!-- 初始餐次表单 -->
                            <div class="meal-card" data-index="0">
                                <button type="button" class="remove-meal" onclick="removeMeal(this)">×</button>
                                <div class="form-row">
                                    <div class="form-col" style="flex: 0 0 20%;">
                                        <div class="form-group">
                                            <label>餐次类型</label>
                                            <select name="form-0-meal_type" class="form-control">
                                                {% for choice in meal_type_choices %}
                                                <option value="{{ choice.0 }}">{{ choice.1 }}</option>
                                                {% endfor %}
                                            </select>
                                        </div>
                                    </div>
                                    <div class="form-col" style="flex: 0 0 30%;">
                                        <div class="form-group">
                                            <label>食物选择</label>
                                            <div class="food-select-wrapper">
                                                <div class="food-select-btn" onclick="toggleDropdown(this)">
                                                    <span class="selected-text">请选择食物</span>
                                                </div>
                                                <input type="hidden" name="form-0-food" class="food-id">
                                                <div class="food-dropdown">
                                                    {% for food in foods %}
                                                    <div class="food-item" onclick="selectFood(this)" data-id="{{ food.food_id }}">
                                                        {{ food.food_name }}
                                                    </div>
                                                    {% endfor %}
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="form-col" style="flex: 0 0 15%;">
                                        <div class="form-group">
                                            <label>数量（克）</label>
                                            <input type="number" 
                                                   name="form-0-quantity" 
                                                   value="100.00" 
                                                   min="0.01" 
                                                   step="0.01" 
                                                   class="form-control">
                                        </div>
                                    </div>
                                    <div class="form-col" style="flex: 0 0 20%;">
                                        <div class="form-group">
                                            <label>用餐时间</label>
                                            <input type="time" 
                                                   name="form-0-meal_time" 
                                                   class="form-control">
                                        </div>
                                    </div>
                                    <div class="form-col" style="flex: 0 0 15%;">
                                        <div class="form-group">
                                            <label>备注</label>
                                            <input type="text" 
                                                   name="form-0-notes" 
                                                   class="form-control">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 添加餐次按钮 -->
                        <button type="button" class="add-meal-btn" onclick="addMeal()">
                            <i class="fa fa-plus"></i> 添加餐次
                        </button>
                    </div>
                    <!-- 操作按钮 -->
                    <div class="btn-group">
                        <button type="button" class="btn btn-default" onclick="window.history.back();">返回</button>
                        <button type="reset" class="btn btn-default">重置</button>
                        <button type="submit" class="btn btn-primary">保存</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</section>
<script>
// 从模型中获取的餐次类型选项
const mealTypeChoices = {{ meal_type_choices|safe }};
// 切换食物下拉框显示/隐藏
function toggleDropdown(element) {
    const dropdown = element.nextElementSibling.nextElementSibling;
    dropdown.classList.toggle('active');
}
// 选择食物
function selectFood(element) {
    const foodId = element.getAttribute('data-id');
    const foodName = element.textContent;
    const wrapper = element.closest('.food-select-wrapper');
    const hiddenInput = wrapper.querySelector('.food-id');
    const selectedText = wrapper.querySelector('.selected-text');
    const dropdown = wrapper.querySelector('.food-dropdown');
    
    // 更新选中状态
    hiddenInput.value = foodId;
    selectedText.textContent = foodName;
    
    // 高亮选中项
    wrapper.querySelectorAll('.food-item').forEach(item => {
        item.classList.remove('selected');
    });
    element.classList.add('selected');
    
    // 关闭下拉框
    dropdown.classList.remove('active');
}
// 点击其他区域关闭下拉框
document.addEventListener('click', function(event) {
    if (!event.target.closest('.food-select-wrapper')) {
        document.querySelectorAll('.food-dropdown').forEach(dropdown => {
            dropdown.classList.remove('active');
        });
    }
});
// 添加新的餐次表单
function addMeal() {
    const container = document.getElementById('meal-container');
    const mealCount = container.children.length;
    const newMeal = document.createElement('div');
    newMeal.className = 'meal-card';
    newMeal.dataset.index = mealCount;
    
    // 构建餐次类型选项HTML
    let mealTypeOptions = '';
    mealTypeChoices.forEach(choice => {
        mealTypeOptions += `<option value="${choice[0]}">${choice[1]}</option>`;
    });
    
    // 构建食物列表HTML
    let foodItems = '';
    {% for food in foods %}
    foodItems += `<div class="food-item" onclick="selectFood(this)" data-id="{{ food.food_id }}">{{ food.food_name }}</div>`;
    {% endfor %}
    
    newMeal.innerHTML = `
        <button type="button" class="remove-meal" onclick="removeMeal(this)">×</button>
        <div class="form-row">
            <div class="form-col" style="flex: 0 0 20%;">
                <div class="form-group">
                    <label>餐次类型</label>
                    <select name="form-${mealCount}-meal_type" class="form-control">
                        ${mealTypeOptions}
                    </select>
                </div>
            </div>
            <div class="form-col" style="flex: 0 0 30%;">
                <div class="form-group">
                    <label>食物选择</label>
                    <div class="food-select-wrapper">
                        <div class="food-select-btn" onclick="toggleDropdown(this)">
                            <span class="selected-text">请选择食物</span>
                        </div>
                        <input type="hidden" name="form-${mealCount}-food" class="food-id">
                        <div class="food-dropdown">
                            ${foodItems}
                        </div>
                    </div>
                </div>
            </div>
            <div class="form-col" style="flex: 0 0 15%;">
                <div class="form-group">
                    <label>数量（克）</label>
                    <input type="number" 
                           name="form-${mealCount}-quantity" 
                           value="100.00" 
                           min="0.01" 
                           step="0.01" 
                           class="form-control">
                </div>
            </div>
            <div class="form-col" style="flex: 0 0 20%;">
                <div class="form-group">
                    <label>用餐时间</label>
                    <input type="time" 
                           name="form-${mealCount}-meal_time" 
                           class="form-control">
                </div>
            </div>
            <div class="form-col" style="flex: 0 0 15%;">
                <div class="form-group">
                    <label>备注</label>
                    <input type="text" 
                           name="form-${mealCount}-notes" 
                           class="form-control">
                </div>
            </div>
        </div>
    `;
    
    container.appendChild(newMeal);
    document.getElementById('id_form-TOTAL_FORMS').value = mealCount + 1;
}
// 移除餐次表单
function removeMeal(button) {
    const container = document.getElementById('meal-container');
    const mealCard = button.closest('.meal-card');
    
    if (container.children.length > 1) {
        mealCard.remove();
        updateMealIndices();
    } else {
        alert('至少需要保留一个餐次');
    }
}
// 更新餐次索引
function updateMealIndices() {
    const container = document.getElementById('meal-container');
    const meals = container.getElementsByClassName('meal-card');
    
    for (let i = 0; i < meals.length; i++) {
        const meal = meals[i];
        meal.dataset.index = i;
        
        meal.querySelectorAll('input, select').forEach(input => {
            if (input.name && input.name.includes('form-')) {
                input.name = input.name.replace(/form-\d+-/, `form-${i}-`);
            }
        });
    }
    
    document.getElementById('id_form-TOTAL_FORMS').value = meals.length;
}
</script>
{% endblock %}